package com.hw.droid.hwcatalog;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ListView;

import hwdroid.app.HWListActivity;
import hwdroid.widget.ItemAdapter;
import hwdroid.widget.ActionBar.ActionBarView.OnRightWidgetItemClick2;
import hwdroid.widget.item.DrawableText2Item;
import hwdroid.widget.item.Item;
import hwdroid.widget.item.Item.Type;
import hwdroid.widget.itemview.ItemView;

import java.util.ArrayList;
import java.util.List;

public class ItemAdapterSample extends HWListActivity{
	
	private CheckBox mAllCheckBox;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.showBackKey(true);
        
    	List<Item> items = new ArrayList<Item>();
    	
	    for(int i = 0; i < 100; i ++) {
	      items.add(new DrawableText2Item("text" + i, "subtext" + i, this.getResources().getDrawable(R.drawable.aui2_5)));
	    }
	  
	    final ItemAdapter adapter = new ItemAdapter(this, items);
	    adapter.setTypeMode(Type.CHECK_MODE);
	    setListAdapter(adapter);
        
	    mAllCheckBox = new CheckBox(this); 
	    mAllCheckBox.setClickable(false);
    	
    	this.setRightWidgetView(mAllCheckBox); 	
    	this.setRightWidgetClickListener2(new OnRightWidgetItemClick2() {

			@Override
			public void onRightWidgetItemClick(View arg0) {
			    CheckBox cb = (CheckBox) arg0;
			    cb.setChecked(!cb.isChecked());
				adapter.doAllSelected(cb.isChecked());
				adapter.notifyDataSetChanged();
				
				setTitle2("selected = "+ adapter.getSelectedCounts());
			}});
    }
    
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	ItemView view = (ItemView) v;    	
    	ItemAdapter adapter = (ItemAdapter)l.getAdapter();
    	Item item = (Item)adapter.getItem(position);
    	item.setChecked(!item.isChecked());
    	view.setObject(item);
    	
    	adapter.setSelectedItem(position);
    	
    	setTitle2("selected = "+ adapter.getSelectedCounts());
    	

    	if(adapter.getSelectedCounts() == adapter.getCount()) {
    		if(!mAllCheckBox.isChecked()) {
    		    mAllCheckBox.setChecked(true);
    	    	
    		}
    	} else {
    		if(mAllCheckBox.isChecked()) {
    		    mAllCheckBox.setChecked(false);
    	    	
    		}
    	}
    }
}
